// 05local/03shopInfo/shopInfo.js
var co = require('../../resource/js/common.js')
var ws = require('../../resource/js/websocket.js')
var Cart = require('shoppingCart.js')
var app = getApp()
var _this, _data, _Room_ID, _isLogin = 0, _opt, _NickName
var _need_keys = ['Products_ID', 'sku', 'unionid']
Page({
   data: {
      cateBtnStateArr: [],
      tableInfo: '',
      Cart_List: [],       //购物车菜单
      foodNum: 0,          //购物车数量
      totalPrice: 0,       //购物车总价
      Cart_Show: 0,        //购物车是否显示
      productSku: [],      //商品属性值
      skuvaList: [],       //商品属性价格
      openSku: false,
      isThis: -1,        // 选择商品规格变色
      selectID: '',
      win_h: 0,
      syh: '',             // 购物车高度
      setGuestNumShow: 0,  //自定义弹窗参数
      numArray: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 0]],
      cateProductsList: [],// 商家分类ID数组
      idx: 0,              //首次进入显示
      self_uid: ''
   },

   onLoad: function (options) {
      _this = this
      _data = this.data
      _opt = options
      _NickName = app.Data.userInfo.User_NickName
      console.log('【】_data【】', _data)
      //获取桌信息
      if (co.empty(_opt.value)) {//空为扫描进入点餐，否则为软件选商家点击进入点餐
         this.getTableOrder()//取桌订单
      } else {
         this.getTableInfo()//取桌信息
      }
      if (co.empty(_opt.Guest_Num)) {
         this.setData({ setGuestNumShow: 1 })
      } else if (_data.tableInfo != '') {
         var objStr = JSON.stringify(_data.tableInfo)
         wx.navigateTo({
            url: '/02local/07tableOrder/tableOrder?obj=' + objStr
         })
      }
      this.setData({
         win_h: wx.getSystemInfoSync().windowHeight - 48, //设置scroll-view高度
         self_uid: app.Data.userInfo.unionid
      })
      this.getCateList()
   },
   //初始化WS,并登录用户
   initWS_Login() {
      _Room_ID = _opt.Biz_ID + '_' + _opt.Table_ID
      ws.initWebsocket(app.Data.userInfo, _Room_ID, function (res) {
         console.log('【wss初始化及登录结果】', res)
      })
      //监听WS
      ws.onSocketMsg(function (res) {
         console.log('【foodInfo页面监听到】', res)
         // console.log('【Cart_List购物车菜单】', _data.Cart_List)
         if (res.type == 'login' && res.unionid == _data.self_uid) {
            _isLogin = 1
            if (res.food_list) {
               //获取同桌人已点的菜单列表var cart_list = 
               _this.mergeSameFood(res.food_list)
            }
         } else if (res.type == 'getFood') {
            // console.log('【加菜参数food_obj】', res.food)
            if (_data.self_uid != res.food.unionid)
               _this.add_ws_food_to_cart(res.food)
         }
      })
   },
   // 首次进收到同桌人已点的菜单,一样的合并
   mergeSameFood: function (list) {
      var new_list = [];
      var len = list.length
      for (var i = 0; i < len; i++) {
         var obj = list[i];
         var index = co.getIndexInList(obj, new_list, _need_keys)
         if (index == -1)
            new_list.push(obj)
         else
            new_list[index].num++
      }
      // console.log('【去重合并后的单new_list】', new_list)
      this.setData({ Cart_List: new_list })
      this.showCartList('', 1)
      this.forShowNumToMenu(new_list, 0)
      this.countNumAndPrice()
      // return new_list
   },
   //加WS菜信息到购物车
   add_ws_food_to_cart(food) {
      console.log("【加菜信息】===", food)
      var Cart_List = _data.Cart_List
      var i = co.getIndexInList(food, Cart_List, _need_keys)
      if (food.num == -2) {
         Cart_List = _this.cartRemainOfClearForUid(food.unionid)
         // Cart_List.splice(i, 1)
      } else {
         if (i == -1) {
            Cart_List.push(food)
         } else {
            Cart_List[i].num += food.num
            if (Cart_List[i].num == 0)
               Cart_List.splice(i, 1)
         }
      }
      this.setData({ Cart_List: Cart_List })
      this.showCartList('', 1)
      this.countNumAndPrice()
   },
   //发送WS加菜减菜
   send_ws_add_food(food) {
      var msg = {
         type: 'getFood',
         food: food
      }
      ws.sendSocketMsg(JSON.stringify(msg), function (res) {
         console.log('【sendSocketMsg:发送成功回调】')
      })
   },
   // 循环显示到菜谱
   forShowNumToMenu: function (Cart_List, index) {
      var C_P_List = _data.cateProductsList
      var goodsList = C_P_List[index]
      for (var key in Cart_List) {
         if (Cart_List[key].unionid == _data.self_uid) {//是自己点的才循环
            for (var k in goodsList) {
               if (goodsList[k].Products_ID == Cart_List[key].Products_ID) {
                  if (co.empty(goodsList[k].num))
                     goodsList[k].num = 0//如果没有先初始为0
                  goodsList[k].num += Cart_List[key].num
               }
            }
         }
      }
      this.setData({ cateProductsList: C_P_List })
   },
   //点击菜谱上加号
   clickMenuAddFood: function (e) {
      var e_id = e.currentTarget.id
      var food = _data.cateProductsList[_data.idx][e_id]
      food = this.reset_food(food)
      this.send_ws_add_food(food)

      var cart_list = _data.Cart_List
      var cart_len = cart_list.length
      var index = co.getIndexInList(food, cart_list, _need_keys)
      if (index == -1) {
         cart_list.push(food)
      } else {
         cart_list[index].num++
      }

      this.setData({
         Cart_List: cart_list,
         openSku: false,
         isThis: -1,
         selectID: e_id
      })
      console.log('【_data.Cart_List】', _data.Cart_List)
      this.countNumAndPrice()
      this.goodsListAddNum()
   },
   //点击菜谱上减号
   clickMenuSubtractFood: function (e) {
      var i = e.currentTarget.id
      var list = _data.cateProductsList[_data.idx]
      var c = 'cateProductsList[' + _data.idx + ']'
      list[i].num--
      this.setData({ [c]: list })
      // 发送减菜信息
      this.send_ws_add_food({
         num: -1,
         Products_ID: list[i].Products_ID,
         sku: '',
         unionid: _data.self_uid
      })
      this.reduceCartList(list[i].Products_ID)
   },
   //菜谱上选中的菜food重置成购物车及发送WS用的新对象
   reset_food(food) {
      var sku = '', sku_id = ''
      //判断属性是否存在
      if (_data.isThis != -1) {
         sku = _data.productSku[_data.idx][_data.selectID]
         sku_id = _data.isThis
      }
      var select_price
      if (sku == '') {
         select_price = food.Products_PriceX
      } else {
         select_price = food.skuval[sku_id].Txt_PriceSon
      }
      var cart_food = {
         Products_ID: food.Products_ID,
         pic: food.Product_homeImg,
         name: food.Products_Name,
         price: select_price,
         num: 1,
         sku: co.empty(sku[_data.isThis]) ? '' : sku[_data.isThis],
         sku_id: sku_id,
         userName: _NickName,
         unionid: _data.self_uid
      }
      console.log('【在菜谱上选中的菜food】', food, '【重置购物车用的新对象】', cart_food)
      return cart_food
   },
   //购物车选中的加菜food重置发送WS用的新对象
   reset_cart_food(cart_food) {
      var new_cart_food = co.addValueForKey({}, cart_food)
      new_cart_food.num = 1
      new_cart_food.userName = _NickName
      new_cart_food.unionid = _data.self_uid
      console.log('【new_cart_food】', new_cart_food)
      return new_cart_food
   },
   //关联购物车里减
   reduceCartList: function (Products_ID) {
      var list = _data.Cart_List
      for (var i = 0; i < list.length; i++) {
         if (Products_ID == list[i].Products_ID && list[i].unionid == _data.self_uid) {
            list[i].num--
            if (list[i].num == 0)
               list.splice(i, 1)
         }
      }
      this.setData({ Cart_List: list })
      this.countNumAndPrice()
   },
   //点击购物车的加号
   clickCartAddFood: function (e) {
      var i = e.currentTarget.id
      var cart_list = _data.Cart_List
      cart_list[i].num++
      this.setData({ Cart_List: cart_list })
      // 发送      
      var ws_food = this.reset_cart_food(cart_list[i])
      this.send_ws_add_food(ws_food)
      this.countNumAndPrice()
      this.plusGoodsList(cart_list[i].Products_ID, 1)
   },
   //点击购物车的减号
   clickCartSubtract: function (e) {
      var i = e.currentTarget.id
      var list = _data.Cart_List
      list[i].num--
      // 发送减菜信息
      this.send_ws_add_food({
         num: -1,
         Products_ID: list[i].Products_ID,
         sku: list[i].sku,
         unionid: _data.self_uid
      })
      this.plusGoodsList(list[i].Products_ID, -1)
      if (list[i].num == 0) {
         list.splice(i, 1)
      }
      this.setData({ Cart_List: list })

      // 关闭购物车
      if (list == 0) {
         this.showMenu()
      }
   },
   //关联菜谱里【加】或【减】，num=1为加，num=-1为减
   plusGoodsList: function (Products_ID, num) {
      var list = _data.cateProductsList[_data.idx]
      var c = 'cateProductsList[' + _data.idx + ']'
      for (var i = 0; i < list.length; i++) {
         if (Products_ID == list[i].Products_ID) {
            if (list[i].num)
               list[i].num += num
            else
               list[i].num = 1
            break
         }
      }
      this.setData({ [c]: list })
      this.countNumAndPrice()
   },
   //菜谱上已点的菜数量加
   goodsListAddNum: function (index) {
      if (co.empty(_data.selectID))
         return
      var list = _data.cateProductsList[_data.idx]
      var obj = list[_data.selectID]
      var c = 'cateProductsList[' + _data.idx + ']'
      if (obj.hasOwnProperty('num')) {
         obj.num++
      } else {
         obj.num = 1
      }
      this.setData({ [c]: list })
   },
   //底部价格数量显示 
   countNumAndPrice: function () {
      var num = 0
      var price = 0
      var list = _data.Cart_List
      // 当添加的商品数量>=7时固定scroll-view高度
      if (list.length > 6) {
         this.setData({ syh: 300 })
      }
      for (var i = 0; i < list.length; i++) {
         num += list[i].num
         price += (list[i].price * list[i].num)
      }
      this.setData({
         foodNum: num,
         totalPrice: parseFloat(price).toFixed(2)
      })
   },
   // 已点菜单结算
   toFoodOrder: function () {
      if (_data.Cart_List.length == 0) {
         wx.showToast({
            title: '您还没点菜哦',
            image: '/resource/img/huaji.png'
         })
         return;
      }
      var tab = _data.tableInfo
      var obj = {
         command: tab.Order_ID ? 'add' : 'eat',
         order: _data.Cart_List,
         Order_ID: tab.Order_ID,
         Table_Cate: tab.Table_Cate,
         Table_No: tab.Table_No,
         Num: _opt.Guest_Num,
         Table_ID: _opt.Table_ID,
         Value: _opt.value
      }
      let orderJSON = JSON.stringify(obj)
      let result_id = co.empty(tab) ? 0 : 1
      wx.navigateTo({
         url: '/02local/04foodOrder/foodOrder?order=' + orderJSON + '&id=' + result_id,
      })
   },
   // 商品分类点击事件
   cateClick: function (e) {
      var index = Number(e.currentTarget.id)
      // 清空属性选择
      this.setData({ idx: index })
      // 获取商品分类数据
      var sort = _data.goodsCateList
      var clickID = sort[index].Category_ID
      //获取下标为index的分类商品列表
      if (co.empty(_data.cateProductsList[index])) {
         this.getGoodsList(clickID, index)
      }
      //渲染分类按钮
      this.renderingCateBtn(index)
   },
   // 获取商家分类数据
   getCateList: function () {
      var param = {
         Biz_ID: _opt.Biz_ID,
      }
      co.getShareApi('biz/Bmg/getBizCategoryList', param, function (res) {
         var c_list = res.data
         if (res.code == 0) {
            _this.setData({ goodsCateList: c_list })//页面用分类数据
            // 加载首页执行首项数据加载
            _this.getGoodsList(c_list[0].Category_ID, 0)
            _this.renderingCateBtn(0)
         }
      })
   },
   //获取商品数据 
   getGoodsList: function (Cate_ID, index) {
      var param = {
         Biz_ID: _opt.Biz_ID,
         Products_BizCategory: Cate_ID,
         pageNo: 0
      }
      var once = _data.cateProductsList         //分类商品数组
      co.getShareApi('product/Pmg/getProductList', param, function (res) {
         if (res.code == 0) {
            once[index] = res.data
            console.log("【获取商品】===", res.data)
            var map = res.data
            var pk = _data.productSku       //商品属性值
            var su = _data.skuvaList        //商品属性价格
            var p = [], u = []
            for (var key in map) {
               if (map[key].sku_list.length > 0) {
                  p.push(map[key].sku_list[0].sku)
               } else {
                  p.push('')
               }
               u.push(map[key].skuval)
            }
            pk[index] = p, su[index] = u
            _this.setData({
               productSku: pk,
               skuvaList: su,
               cateProductsList: once
            })
            if (!_isLogin) {
               _this.initWS_Login()
            }
            var CartList = _data.Cart_List
            if (CartList != '') {
               _this.forShowNumToMenu(CartList, index)
            }
         }
         // console.log("【存入的属性值】", __data.productSku)
         // console.log("【存入的属性价格】", __data.skuvaList)
         // console.log("【存入的商品】", __data.cateProductsList)
      })
   },
   //渲染分类按钮
   renderingCateBtn: function (index) {
      var btnStateArr = []
      var num = _data.goodsCateList.length
      for (var i = 0; i < num; i++) {
         btnStateArr.push(false)
      }
      btnStateArr[index] = true
      this.setData({ cateBtnStateArr: btnStateArr })
   },
   // 弹起购物车清单底部显示
   showCartList: function (e, isShow) {
      var show = !co.empty(isShow) ? isShow : _data.Cart_Show ? 0 : 1
      this.setData({ Cart_Show: show })
      // 当添加的商品数量>=7时固定scroll-view高度
      if (_data.Cart_List.length >= 7) {
         this.setData({ syh: 300 })
      }
   },
   //设置人数
   setGuestNum: function (e) {
      var num = e.currentTarget.id
      if (num > 0) {
         this.setData({
            setGuestNumShow: 0,
            num: num
         })
      } else {
         this.setData({ numArray: app.reSetNum(_data.numArray, num, 15) })
      }
   },
   // //重设数字
   // reSetNum: function (num) {
   //    var nA = _data.numArray
   //    for (var i = 0; i < nA.length; i++) {
   //       var nA2 = nA[i]
   //       for (var j = 0; j < nA2.length; j++) {
   //          if (num == 0) {
   //             if (nA[i][j] == 15) nA[i][j] = -1
   //             else if (nA[i][j] > 15) nA[i][j] += 14
   //             else if (nA[i][j] > 0) nA[i][j] += 15
   //          } else {
   //             if (nA[i][j - 1] == 14) nA[i][j] = 15
   //             else if (nA[i][j] > 29) nA[i][j] -= 14
   //             else if (nA[i][j] > 0) nA[i][j] -= 15
   //          }
   //       }
   //    }
   //    this.setData({ numArray: nA })
   // },
   // 扫码进入时获取桌订单
   getTableOrder: function (bizID, tableID) {
      var param = { Biz_ID: bizID, Table_ID: tableID }
      co.getShareApi('order/Omg/tableOrder', param, function (res) {
         // console.log("【获取桌子订单】===", res.data)
         var table = res.data
         if (res.code == 0) {
            _this.setData({ tableInfo: table })
            wx.setNavigationBarTitle({ title: table.Table_Label })
         }
      })
   },
   //非扫描进入获取桌信息，显示页面标题
   getTableInfo() {
      var param = co.addValueForKey({}, _opt, ['Biz_ID', 'Table_ID'])
      co.getMealApi('table/Tmg/getAllTableList', param, function (res) {
         // console.log("【获取桌子订单】===", res.data)
         var d = res.data
         if (res.code == 0) {
            wx.setNavigationBarTitle({ title: d.Table_Cate + d.Table_No + '桌' })
         }
      })
   },
   // 显示和关闭商品属性选择
   showToast: function (e) {
      this.setData({ openSku: true, selectID: e.currentTarget.id, isThis: 1 })
   },

   closeSku: function () {
      this.setData({ openSku: false, isThis: -1 })
   },
   // 选择属性变色
   selectAttribute: function (e) {
      this.setData({ isThis: e.currentTarget.id })    //获取点击的属性位置
   },
   // 多规格商品删除提示
   showTitle: function () {
      co.Modal('多规格商品需要到购物车删除', '朕知道了')
   },
   // 清空购物车里所有我点的
   clearCartMyAddFood: function () {
      co.confirm('清空我点的！', '取消', '确认', function (res) {
         if (res == true) {
            //将菜单上所有我点的数量清零
            var list = _data.cateProductsList
            for (var i = 0; i < list.length; i++) {
               for (var j = 0; j < list[i].length; j++) {
                  list[i][j].num = 0
               }
            }
            //发送删除我点的到WS
            _this.send_ws_add_food({
               num: -2,
               unionid: _data.self_uid
            })
            _this.setData({
               Cart_List: _this.cartRemainOfClearForUid(_data.self_uid),
               // foodNum: 0,
               // totalPrice: 0,
               syh: '',
               cateProductsList: list,
               isSelf: false
            })
            _this.countNumAndPrice()
         }
      })
   },
   //将购物车上某人点的全部删除后，返回剩下的
   cartRemainOfClearForUid(who_unionid) {
      var c_list = _data.Cart_List, Cart_Remain = []
      for (var i = 0; i < c_list.length; i++) {
         if (c_list[i].unionid != who_unionid) {
            Cart_Remain.push(c_list[i])
         }
      }
      return Cart_Remain
   },
   // 页面卸载清除ws连接
   onUnload: function () {
      var msg = JSON.stringify({ type: 'logout' })
      ws.sendSocketMsg(msg, function (res) {
         console.log('【退出WS结果】', res)
         _isLogin = 0
      })
   },
})
